package cc.rengu.igas.share.common.util;

import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

public class HttpUtil {
    RgLogger rglog = RgLog.getLogger(this.getClass().getName());

    /**
     * 发送POST请求
     *
     * @param httpUrl  请求URL
     * @param postData 发送的数据
     * @return 响应数据
     */
    public String post(String httpUrl, String postData) {
        OutputStreamWriter outputStreamWriter = null;
        HttpURLConnection connection = null;
        InputStream inStream = null;
        try {
            rglog.info("请求URL:{},请求数据:{}", httpUrl, postData);
            URL postUrl = new URL(httpUrl);
            connection = (HttpURLConnection) postUrl.openConnection();
            /* 设置连接主机超时（单位：毫秒）*/
            connection.setConnectTimeout(2000);
            /* 设置从主机读取数据超时（单位：毫秒）*/
            connection.setReadTimeout(2000);
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            /* 建立与服务器的连接，并未发送数据 */
            connection.connect();
            outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
            outputStreamWriter.write(postData);
            outputStreamWriter.flush();
            outputStreamWriter.close();
            if (connection.getResponseCode() == 200) {
                /* 发送数据到服务器并使用Reader读取返回的数据 */
                StringBuilder sBuffer = new StringBuilder();

                byte[] buf = new byte[1024];
                inStream = connection.getInputStream();
                for (int n; (n = inStream.read(buf)) != -1; ) {
                    sBuffer.append(new String(buf, 0, n, StandardCharsets.UTF_8));
                }
                inStream.close();
                connection.disconnect();
                return sBuffer.toString();
            }
        } catch (Exception e) {
            rglog.error(e.getMessage());
        } finally {
            if (null != outputStreamWriter) {
                try {
                    outputStreamWriter.close();
                } catch (IOException e) {
                }
            }
            if (null != inStream) {
                try {
                    inStream.close();
                } catch (IOException e) {

                }
            }
            if (null != connection) {
                connection.disconnect();
            }
        }
        return null;
    }

    /**
     * 发送GET请求
     *
     * @param httpUrl  GET请求URL
     * @param paramMap GET请求参数
     * @return 响应数据
     */
    public String get(String httpUrl, Map<String, String> paramMap) {
        BufferedReader in = null;
        try {
            if (StringUtil.isEmptyOrNull(httpUrl)) {
                return null;
            }
            String getUrlString = generateHttpUrl(httpUrl, paramMap);
            rglog.info("请求URL：{}", getUrlString);
            URL getUrl = new URL(getUrlString);
            /* 打开和URL之间的连接 */
            URLConnection connection = getUrl.openConnection();
            /* 建立实际的连接 */
            connection.connect();
            /* 获取所有响应头字段 */
            Map<String, List<String>> map = connection.getHeaderFields();
            /* 获取调用结果 */
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder result = new StringBuilder();
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        } catch (Exception e) {
            rglog.error(e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
            }
        }
        return null;
    }

    /**
     * 根据配置拼装URL地址
     *
     * @param httpUrl  URL地址
     * @param paramMap URL参数集合
     * @return URL地址
     */
    private String generateHttpUrl(String httpUrl, Map<String, String> paramMap) {
        if (null == paramMap) {
            return httpUrl;
        }
        StringBuilder requestUrlParam = new StringBuilder();
        for (String key : paramMap.keySet()) {
            requestUrlParam.append(key).append("=").append(paramMap.get(key)).append("&");
        }
        if (httpUrl.trim().endsWith("?")) {
            return httpUrl + requestUrlParam.substring(0, requestUrlParam.length() - 1);
        } else {
            return httpUrl + "?" + requestUrlParam.substring(0, requestUrlParam.length() - 1);
        }
    }

    /**
     * 发送POST请求
     *
     * @param httpUrl     请求URL
     * @param postData    发送的数据
     * @param reqParamMap 请求参数MAP
     * @return 响应数据
     */
    public String post(String httpUrl, String postData, Map<String, String> reqParamMap) {
        OutputStreamWriter outputStreamWriter = null;
        HttpURLConnection connection = null;
        InputStream inStream = null;
        try {
            rglog.info("请求URL:{},请求数据:{}", httpUrl, postData);
            URL postUrl = new URL(httpUrl);
            connection = (HttpURLConnection) postUrl.openConnection();
            /* 设置连接主机超时（单位：毫秒）*/
            connection.setConnectTimeout(2000);
            /* 设置从主机读取数据超时（单位：毫秒）*/
            connection.setReadTimeout(2000);
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //请求参数设置
            for (Map.Entry<String, String> map : reqParamMap.entrySet()) {
                connection.setRequestProperty(map.getKey(), map.getValue());
            }
            /* 建立与服务器的连接，并未发送数据 */
            connection.connect();
            outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
            outputStreamWriter.write(postData);
            outputStreamWriter.flush();
            outputStreamWriter.close();
            if (connection.getResponseCode() == 200) {
                /* 发送数据到服务器并使用Reader读取返回的数据 */
                StringBuilder sBuffer = new StringBuilder();

                byte[] buf = new byte[1024];
                inStream = connection.getInputStream();
                for (int n; (n = inStream.read(buf)) != -1; ) {
                    sBuffer.append(new String(buf, 0, n, StandardCharsets.UTF_8));
                }
                inStream.close();
                connection.disconnect();
                return sBuffer.toString();
            }
        } catch (Exception e) {
            rglog.error(e.getMessage());
        } finally {
            if (null != outputStreamWriter) {
                try {
                    outputStreamWriter.close();
                } catch (IOException e) {
                }
            }

            if (null != inStream) {
                try {
                    inStream.close();
                } catch (IOException e) {

                }
            }
            if (null != connection) {
                connection.disconnect();
            }

        }
        return null;
    }

}
